package com.thinkit.security.custom;

import cn.hutool.json.JSONUtil;
import com.thinkit.utils.model.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        log.error("------------用户权限异常-------------"+request.getRequestURI());
		response.setStatus(HttpStatus.FORBIDDEN.value());
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(JSONUtil.toJsonStr(ApiResult.result(HttpStatus.FORBIDDEN.value(),"您的权限不足!")));
	}

}
